<template>
  <div class="wrap">
    <div class="header">
      <div class="header-title">
        <span>量方称重扫码一体机</span>
        <span class="font-red">入库模式（收货）</span>
      </div>
    </div>
    <div class="content" v-loading="loading">
      <div>
        <w-s-socket></w-s-socket>
      </div>
      <div class="content-card">
        <div class="card-item">
          <span class="label">正在接收：</span>
          <span class="text">{{totalShipmentNum}}单</span>
        </div>
        <div class="card-item">
          <span class="label">总接收进度：</span>
          <span class="text">
            <num2 :right-num="totalShipmentBoxNum" :left-num="receivedShipmentBoxNum" style="display: inline-block"></num2>
          </span>
        </div>
        <div class="card-item">
          <span class="label">选择接收：</span>
          <span class="text">{{chooseShipmentNum}}单</span>
        </div>
        <div class="card-item">
          <span class="label">选择接收进度：</span>
          <span class="text">
            <num2 :right-num="chooseShipmentBoxNum" :left-num="chooseReceivedShipmentBoxNum" style="display: inline-block"></num2>
          </span>
        </div>
      </div>

      <div class="user-btn">
        <el-radio-group v-model="currentUserId" size="medium" @change="switchUserId">
          <el-radio-button label="all">全部({{totalShipmentNum}})</el-radio-button>
          <el-radio-button
            v-for="item in userList"
            :key="item.userId"
            :label="item.userId"
          >
            {{item.userAccount}}({{item.shipmentNum}})
          </el-radio-button>
        </el-radio-group>
      </div>

      <div class="main-content">
        <div class="nav">
          <div class="nav-item" style="font-size: 14px">
            <el-checkbox :indeterminate="indeterminate" :value="checkAll" @change="chooseAllShipment">全选</el-checkbox>
          </div>
          <div
            v-for="item in showShipmentList"
            :key="item.id"
            class="nav-item"
            :class="{active: currentShipmentId === item.id}"
            @click="switchShipment(item.id)"
          >
            <el-checkbox v-model="submitForm.shipmentIds" :label="item.id">{{ item.shipmentNo }}</el-checkbox>
          </div>

        </div>
        <div class="main-shipment">
          <box-scan-shipment :shipment="currentShipment" v-if="currentShipment"></box-scan-shipment>
          <div class="footer-nav">
            <el-button type="primary" :disabled="this.submitForm.shipmentIds.length === 0" @click="showSubmitDialog">确认接收</el-button>
          </div>
        </div>
      </div>

    </div>
    <el-dialog
      title="确认接收以下货件单？"
      :visible.sync="submitDialog"
      class="submit-dialog"
      width="500px"
    >
      <div class="shipment-steps">
        <div class="font-bold f16 mgb10">货件接收进度：</div>
        <div
          v-for="item in chooseShipmentList"
          :key="item.id"
        >
          <span>{{item.shipmentNo}}：</span>
          <span><num2 :right-num="item.exBoxNum" :left-num="getShipmentReceived(item)" style="display: inline-block"></num2></span>
        </div>
        <div class="mgt20">
          <span class="font-bold f16">
            总接收进度：<num2 :left-num="chooseReceivedShipmentBoxNum" :right-num="chooseShipmentBoxNum" style="display: inline-block"></num2>
          </span>
        </div>
        <div class="mgt10 font-red f18">
          确认接收后，未接收的货件仍可通过扫描接收，但扫描后货件单 不会再显示到当前收货界面
        </div>
      </div>
      <template #footer>
        <el-button @click="submitDialog = false;">取消</el-button>
        <el-button type="primary" @click="submitShipment">确认接收</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import WSSocket from "@/views/shipment/components/WSSocket.vue";
import Num2 from "@/components/Common/Num2.vue";
import BoxScanShipment from "@/views/hardware/components/boxScanShipment.vue";
import {EventBus} from "@/utils/eventBus";
import {getShipmentInfo} from "@/api/shipment";
import {deepCopy} from "@/utils";
import {STATUS_RECEIVED} from "@/utils/boxLabel";
import request from "@/utils/request";

export default {
  name: "boxSizeHD",
  components: {BoxScanShipment, Num2, WSSocket},
  computed: {
    // 总的货件单数
    totalShipmentNum(){
      return this.allShipment.length
    },
    // 总的货件单箱子数
    totalShipmentBoxNum(){
      return this.allShipment.reduce((total, item) => total + item.exBoxNum, 0);
    },
    // 已接收的箱子数
    receivedShipmentBoxNum(){
      const set = new Set()
      this.allShipment.forEach(shipment=>{
        shipment.boxLabelList.forEach(item=>{
          if(item.isReceived === 1){
            set.add(item.boxId)
          }
        })
      })
      return set.size;
    },
    // 当前的货件单
    currentShipment(){
      return this.allShipment.find(item => item.id === this.currentShipmentId)
    },
    // 用户列表
    userList(){
      const arr = [];
      this.allShipment.forEach(item=>{
        if(arr.find((user)=> user.userId === item.userId)){
          return
        }
        const obj = {
          userId: item.userId,
          userAccount: item.userAccount,
          shipmentNum: this.allShipment.filter(shipment => shipment.userId === item.userId).length
        }
        arr.push(obj)
      })
      return arr
    },
    // 展示的货件单列表
    showShipmentList(){
      if(this.currentUserId === 'all'){
        return this.allShipment
      }
      return this.allShipment.filter(item => item.userId === this.currentUserId)
    },
    // 选择的货件单列表
    chooseShipmentList(){
      return this.allShipment.filter(item => this.submitForm.shipmentIds.includes(item.id))
    },
    // 选择的货件单数
    chooseShipmentNum(){
      return this.chooseShipmentList.length
    },
    // 选择的货件单箱子数
    chooseShipmentBoxNum(){
      return this.chooseShipmentList.reduce((total, item) => total + item.exBoxNum, 0);
    },
    // 选择接收的箱子数
    chooseReceivedShipmentBoxNum(){
      const set = new Set()
      this.chooseShipmentList.forEach(shipment=>{
        shipment.boxLabelList.forEach(item=>{
          if(item.isReceived === 1){
            set.add(item.boxId)
          }
        })
      })
      return set.size;
    },
    indeterminate(){
      if(this.checkAll){
        return false
      }
      if(this.submitForm.shipmentIds.length === 0){
        return false
      }
      return true
    },
    checkAll(){
      return this.showShipmentList.length === this.submitForm.shipmentIds.length
    },
  },
  data(){
    return {
      allShipment: [], // 所有的货件单
      currentUserId: 'all', // 当前选择的用户
      currentShipmentId: 0, // 当前的货件单id
      submitForm: {
        shipmentIds: [],
      },
      loading: false,
      submitDialog: false,
    }
  },
  created() {
    // 对接socket
    EventBus.$off('boxScan')
    EventBus.$on('boxScan', this.boxScan)

    EventBus.$off('boxScanFail')
    EventBus.$on('boxScanFail', this.boxScanFail)

    // 箱唛改变
    EventBus.$off('changeBox')
    EventBus.$on('changeBox', this.changeBox)

    // this.getShipment(355)
    // this.getShipment(356)
    // this.getShipment(357)
    // this.getShipment(361)
  },
  methods: {

    changeBox(){
      this.getShipment(this.currentShipmentId)
    },
    // 箱唛扫描
    boxScan(data){
      if(!data || !data.boxId){
        return;
      }
      const {shipmentId, boxId} = data;
      const shipment = this.allShipment.find(item => item.id === shipmentId);
      this.$sMsg(boxId + '箱唛扫描成功');
      this.switchShipment(shipmentId)
      if(!shipment){
        this.getShipment(shipmentId)
      }else{
        // 不请求接口 直接改数据
        this.boxDataChange(data)
      }
    },
    boxScanFail(data){
      this.$eMsg('当前扫描货件箱唛不存在或已接收，请重新扫描。若扫码结果有误，请联系技术人员处理');
    },
    // 变更箱唛数据
    boxDataChange(data){
      const {boxId, height, length, weight, width, calWeight} = data
      EventBus.$emit('changeBox', data);
      this.currentShipment.boxLabelList.filter(item => item.boxId === boxId)
        .forEach(item=>{
          item.height = height
          item.length = length
          item.weight = weight
          item.width = width
          item.calWeight = calWeight

          item.volumeWeight = parseFloat((width * height * length / 6000).toFixed(3))
          item.squareNumber = parseFloat((width * height * length / 1000000).toFixed(5))
          item.status = STATUS_RECEIVED
          item.isReceived = 1
          item.isReceiveExcept = 0
        })
    },
    // 获取货件单数据
    getShipment(id){
      this.loading = true
      getShipmentInfo(id)
        .then(res=>{
          this.loading = false
          const {data} = res
          this.pushShipment(data)
        })
    },
    pushShipment(data){
      let shipment = this.allShipment.find(item => item.id === data.id);
      if(!shipment){
        this.allShipment.push(data)
        if(this.allShipment.length === 1){
          this.currentShipmentId = data.id
        }
      }else{
        shipment.boxLabelList = deepCopy(data.boxLabelList)
      }
    },
    // 切换货件单
    switchShipment(id){
      this.currentShipmentId = id;
    },
    switchUserId(){
      if(this.currentUserId === 'all'){
        return;
      }
      this.allShipment.filter(item => item.userId !== this.currentUserId)
        .forEach(item=>{
          const shipmentId = item.id
          const index = this.submitForm.shipmentIds.findIndex(shipmentId)
          if(shipmentId !== -1){
            this.submitForm.shipmentIds.splice(index, 1)
          }

        })
      if(this.currentShipment && this.currentShipment.userId !== this.currentUserId){
        this.currentShipmentId = this.showShipmentList[0].id
      }
    },
    // 选择所有货件单
    chooseAllShipment(){
      if(!this.checkAll){
        this.submitForm.shipmentIds = [];
        this.submitForm.shipmentIds = this.showShipmentList.map(item => item.id)
      }else{
        this.submitForm.shipmentIds = []
      }
    },
    // 提交货件单
    showSubmitDialog(){
      if(this.submitForm.shipmentIds.length === 0){
        return;
      }
      this.submitDialog = true;
    },
    // 获取货件单已接收的箱子数量
    getShipmentReceived(shipment){
      const set = new Set()
      shipment.boxLabelList.forEach(item=>{
        if(item.isReceived){
          set.add(item.boxId)
        }
      })
      return set.size
    },
    submitShipment(){
      this.loading = true;
      this.submitDialog = false;
      const data = deepCopy(this.submitForm)
      request({
        url: '/shipmentV2/batchShipmentReceive',
        method: 'put',
        handleError: true,
        data: data,
      })
        .then(res=>{
          this.loading = false
          if(res.error !== 0){
            this.$eMsg(res.message)
          }else{
            this.$sMsg(res.message)
            this.successSubmit()
          }
        })
    },
    // 成功提交货件单后
    successSubmit(){
      // 移除货件单数据
      this.submitForm.shipmentIds.forEach(shipmentId=>{
        const index = this.allShipment.findIndex(item => item.id === shipmentId)
        if(index !== -1){
          this.allShipment.splice(index, 1)
        }
      })

      // 重置成空数组
      this.submitForm.shipmentIds = []

      // 用户筛选改变
      const userIndex = this.userList.findIndex(item => item.userId === this.currentUserId)
      if(userIndex === -1){
        this.currentUserId = 'all';
      }

      // 当前选择的显示的货件单改变
      this.currentShipmentId = 0;
      if(this.showShipmentList.length > 0){
        this.currentShipmentId = this.showShipmentList[0].id
      }

    }
  }

}
</script>


<style scoped lang="scss">
$border-color: #d7d7d7;
$border-active-color: #1890ff;
.wrap {
  padding: 20px 30px;
  .header{
    .header-title{
      font-weight: bold;
      font-size: 26px;
    }
  }
  .content{
    margin-top: 10px;
    .content-card{
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 20px 20px;
      background: #f2f2f2;
      .card-item{
        margin: 5px 0;
      }
    }
    .user-btn{
      margin: 10px 0;
    }
    .main-content{
      display: flex;
      border: 1px solid $border-color;
      flex-direction: row;
      justify-content: flex-start;
      height: calc(100vh - 420px);
      .nav{
        min-width: 180px;
        height: 100%;
        border-right: 1px solid $border-color;
        overflow: auto;
        .nav-item{
          line-height: 40px;
          padding: 0 15px;
          border-bottom: 1px solid $border-color;
          cursor: pointer;
        }
        .nav-item:hover{
          background: #f2f2f2;
        }
        .nav-item.active{
          border-right: 2px solid $border-active-color;
          background: #E6F7FF;
        }
      }
      .main-shipment{
        height: calc(100% - 25px);
        width: calc(100% - 180px);
        overflow: auto;
        .footer-nav{
          width: calc(100% - 240px);
          border-top: 1px solid $border-color;
          position: absolute;
          bottom: 25px;
          padding: 5px 5px 0 5px;
        }
      }
    }
  }

}
.submit-dialog{
}
</style>
